import os
import logging
from typing import Any, Dict

from langchain.memory import ConversationBufferMemory
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, ConversationalAgent
from langchain_core.prompts import PromptTemplate

from .tools.resume_tool import build_resume_tools
from .tools.job_tool import build_job_tools
from .tools.knowledge_tool import build_knowledge_tools


logger = logging.getLogger(__name__)


class BossAgent:
    # 类级别的会话记忆存储
    _session_memories = {}
    
    def __init__(self) -> None:
        self.llm = ChatOpenAI(
            model_name="qwen-plus",
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
            temperature=0
        )
        self.tools = build_resume_tools() + build_job_tools() + build_knowledge_tools()

        prompt = PromptTemplate(
            template=(
                "你是Boss智能体，严格输出纯文本，不要使用emoji/HTML/特殊字符。\n"
                "行为准则：\n"
                "- 当用户询问岗位，默认直接调用职位检索工具返回前10条岗位明细(JSON)，不反问。\n"
                "- 若条件不足也要给出默认结果，并在结尾附'可继续按城市/薪资/经验收紧'提示。\n"
                "- 回答中禁止HTML/emoji，仅中文与基础标点。\n"
                "- 能够记住之前的对话内容，包括生成的简历、分析结果等。\n\n"
                "历史对话：\n{chat_history}\n\n当前问题：{input}\n\n可用工具：\n{tools}\n\n"
                "如需使用工具，请按如下格式：\nAction: 工具名\nAction Input: 参数\n"
            ),
            input_variables=["input", "chat_history", "tools"],
            partial_variables={
                "tools": "\n".join([f"- {t.name}：{t.description}" for t in self.tools])
            }
        )
        
        self.prompt = prompt

    def _get_or_create_memory(self, session_id: str) -> ConversationBufferMemory:
        """获取或创建会话记忆"""
        if session_id not in self._session_memories:
            self._session_memories[session_id] = ConversationBufferMemory(
                memory_key="chat_history",
                return_messages=True
            )
        return self._session_memories[session_id]

    def run(self, question: str, user_id: int, session_id: str | None = None) -> Dict[str, Any]:
        # 如果没有session_id，使用user_id作为默认session_id
        if not session_id:
            session_id = f"user_{user_id}_default"
        
        # 获取或创建该会话的记忆
        memory = self._get_or_create_memory(session_id)
        
        # 创建agent和executor（每次都需要重新创建，因为memory会变化）
        agent = ConversationalAgent.from_llm_and_tools(
            tools=self.tools,
            llm=self.llm,
            memory=memory,
            prompt=self.prompt,
            verbose=True
        )
        executor = AgentExecutor(
            agent=agent,
            tools=self.tools,
            verbose=True,
            handle_parsing_errors=True,
            max_iterations=8,
            memory=memory
        )
        
        # 执行对话
        result = executor.invoke({一下项目
            "input": question
        })
        return {"response": result.get("output", "")}


